﻿using BW.EatRabbit.API.Application.Commands;
using BW.EatRabbit.API.Dtos;
using BW.EatRabbit.Domain;
using BW.EatRabbit.ErrorCode;
using BW.EatRabbit.Infrastructure.Interfaces;
using MD5Hash;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace BW.EatRabbit.API.Application.CommandHandlers
{
    public class LoginQueryCommandHandler : IRequestHandler<LoginQueryCommand, APIResult<UserDTO>>
    {
        /// <summary>
        /// 用户仓储
        /// </summary>
        private readonly IBaseRepository<User> userRepository;
        /// <summary>
        /// 角色仓储
        /// </summary>
        private readonly IBaseRepository<Role> roleRepository;
        /// <summary>
        /// 角色用户仓储
        /// </summary>
        private readonly IBaseRepository<RoleUser> roleuserRepository;
        private readonly IConfiguration _configuration;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="userRepository">用户仓储</param>
        /// <param name="roleRepository">角色仓储</param>
        public LoginQueryCommandHandler(IBaseRepository<User> userRepository, IBaseRepository<Role> roleRepository,IBaseRepository<RoleUser> roleuserRepository, IConfiguration configuration)
        {
            this.userRepository = userRepository;
            this.roleRepository = roleRepository;
            this.roleuserRepository = roleuserRepository;
            _configuration = configuration;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回登录的任务</returns>
        public Task<APIResult<UserDTO>> Handle(LoginQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<UserDTO> result = new APIResult<UserDTO>();
            var account = userRepository.GetAll().Where(x => x.UserName == request.UserName).FirstOrDefault();
            if(account==null)
            {
                result.Code = ResultCode.登录失败;
                result.Message = ResultCode.登录失败.ToString() + "用户不存在";
                return Task.FromResult(result);
            }
            //MD5加密
            request.UserPass = request.UserPass.GetMD5().ToUpper();
            if(account.UserPass!=request.UserPass)
            {
                result.Code = ResultCode.登录失败;
                result.Message = ResultCode.登录失败.ToString() + "用户名和密码不匹配";
                return Task.FromResult(result);
            }
          
            //
            var roleaccount = roleuserRepository.GetAll().Where(x => x.UserId == account.UserId).FirstOrDefault();
            if(roleaccount==null)
            {
                result.Code = ResultCode.登录失败;
                result.Message = ResultCode.登录失败.ToString() + "请联系管理员给您配置相应的角色";
                return Task.FromResult(result);
            }
            var role = roleRepository.GetAll().Where(x => x.RoleId == roleaccount.RoleId).FirstOrDefault();
            if(role==null)
            {
                result.Code = ResultCode.登录失败;
                result.Message = ResultCode.登录失败.ToString() + "请联系管理员给您分配角色";
                return Task.FromResult(result);
            }
            UserDTO entity = new UserDTO()
            {
                UserId= account.UserId,
                UserName= account.UserName,
                UserNickname= account.UserNickname,
                RoleId=role.RoleId,
                RoleName=role.RoleName
            };
            result.Data = entity;
            entity.Token = CreateTokenString(entity);
            result.Code = ResultCode.登录成功;
            result.Message = ResultCode.登录成功.ToString();
           
            return Task.FromResult(result);



        }
        /// <summary>/// 生成 JWT Token（令牌）/// </summary>/// <returns></returns>
        private string CreateTokenString<T>(T user) where T : class 
        {
            //私钥
            var secretByte = Encoding.UTF8.GetBytes(_configuration["JWTConfiguration:SecretKey"]);
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            //所有权
            var claims = new List<Claim>();
            var type = typeof(T);
            foreach (var item in type.GetProperties())
            {
                var name = item.Name;
                var value=item.GetValue(user);
                Claim claim = new Claim(name, value?.ToString() ?? "");
                claims.Add(claim);
            }
         
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: "BeiJingBW",
                audience: "BeiJingBW",
                claims: claims,
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }
    }
}
